package com.wmyg.antifake.controller;

import com.wmyg.antifake.entity.Factory;
import com.wmyg.antifake.service.FactoryService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.security.Principal;
import java.util.List;

/**
 * @author 王卓逸
 * @program TODO
 * @description TODO
 * @create 2019-05-20
 */
@RestController
@RequestMapping(value = "/factory")
@Api(description = "生产基地相关接口")
public class FactoryController {

    @Autowired
    FactoryService factoryService;

    @PreAuthorize("hasAuthority('addfactory')")
    @PostMapping(value = "/factory")
    @ApiOperation(value = "添加生产基地", notes = "添加操作不能传入id", response = Boolean.class)
    public Boolean saveFactory(Factory factory, @ApiIgnore Principal principal) {
        return factoryService.saveFactory(factory, principal.getName());
    }

    @PreAuthorize("hasAuthority('createcode')")
    @GetMapping(value = "/factories")
    @ApiOperation(value = "下拉菜单内的生产基地列表")
    public List<Factory> getFactoryList(@ApiIgnore Principal principal) {
        return factoryService.getFactoryList(principal.getName());
    }

    @PreAuthorize("hasAuthority('factory')")
    @GetMapping(value = "/factorypage")
    @ApiOperation(value = "生产基地按页按条件查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "index", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "factoryName", value = "生产基地名称模糊查询字段", required = false, dataType = "String")
    })
    public Page<Factory> getFactoryPage(@ApiIgnore Principal principal, Integer index, String factoryName) {
        if (StringUtils.isBlank(factoryName)) {
            return factoryService.getFactoryPage(principal.getName(), index);
        } else {
            return factoryService.getFactoryPage(principal.getName(), index, factoryName);
        }
    }

    @PreAuthorize("hasAuthority('addfactory') or hasAuthority('factory')")
    @PutMapping(value = "/factory")
    @ApiOperation(value = "更改生产基地", notes = "更改操作必须传入id", response = Boolean.class)
    public Boolean updateFactory(Factory factory, @ApiIgnore Principal principal) {
        return factoryService.saveFactory(factory, principal.getName());
    }

    @PreAuthorize("hasAuthority('addfactory') or hasAuthority('factory')")
    @GetMapping(value = "/factory")
    @ApiOperation(value = "根据Id获取单个生产基地名称")
    @ApiImplicitParam(name = "factoryId", value = "生产基地Id", required = true, dataType = "Integer")
    public Factory getFactory(Integer factoryId) {
        return factoryService.findByFactoryId(factoryId);
    }

}
